//
//  MyViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/19.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "MyViewController.h"
#import "LanguageChangeViewController.h"
#import "MyDepositSlipViewController.h"
#import "InviteFriendsViewController.h"
#import "VerifiedViewController.h"
#import "SettingPassWordViewController.h"
#import "UserInfoChangeViewController.h"
#import "WithdrawViewController.h"
//#import "AboutUSViewController.h"
#import "WCOrderAndAddrVC.h"
#import "WContactUSVC.h"
#import "MyTopView.h"
#import "MyCell.h"
#import "UserManager.h"
#import "Bolts.h"

@interface MyViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@property (nonatomic, strong) UITableView  *tableView;
@property (nonatomic, strong) MyTopView    *topView;
@property (nonatomic, strong) NSArray      *cellDataArray;
@property (nonatomic, strong) UIButton     *subMitBtn;
@property (nonatomic, assign) NSInteger    level;

@end

@implementation MyViewController

#pragma mark - VC Life

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    self.cellDataArray = @[@{@"image":@"wode_cundan",
                             @"title":kLocalizedString(@"我的收益", nil)},
                           @{@"image":@"mine_yingjian",
                             @"title":kLocalizedString(@"PC硬件", nil)},
                           @{@"image":@"mine_yaoqing",
                             @"title":kLocalizedString(@"邀请好友", nil)},
                           @{@"image":@"wode_mimashezhi",
                             @"title":kLocalizedString(@"密码设置", nil)},
                           @{@"image":@"wode_yuyanqiehuan",
                             @"title":kLocalizedString(@"语言切换", nil)},
                           @{@"image":@"wode_gengxin",
                             @"title":kLocalizedString(@"检查更新", nil)}];
    
//    @{@"image":@"mine_contact",
//      @"title":kLocalizedString(@"联系我们", nil)},
      
    self.level = 0;
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeUserInfo:) name:@"changeUserInfo" object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarHidden = NO;
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [self allRequest];
}

#pragma mark - NSNotificationAction

- (void)changeUserInfo:(NSNotification *)no
{
    if ([no.userInfo[@"type"] isEqualToString:@"image"]) {
        self.topView.userImageView.image = no.userInfo[@"image"];
    }else if ([no.userInfo[@"type"] isEqualToString:@"userName"]){
        self.topView.userNameLabel.text = [CBTLocalUserManager sharedInstance].nickName;
    }
}

#pragma mark - OthersAction
- (BFTask *)getAssetMsg
{
    BFTaskCompletionSource *source = [BFTaskCompletionSource taskCompletionSource];
    
    [UserManager getAssetMsgWithUserId:[CBTLocalUserManager sharedInstance].userId block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal) {
            NSString *userAsset = [data[@"data"]objectForKey:@"asset"];
            NSInteger level = [[data[@"data"]objectForKey:@"userStar"] integerValue];
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@",data[@"data"][@"address"]] forKey:@"address"];
            [[NSUserDefaults standardUserDefaults]synchronize];

            [self updateLevel:level];
            
            userAsset = [userAsset floatValue] <= 0 ? @"0" : userAsset;
            [[CBTLocalUserManager sharedInstance] refreshUserInfoDic:@{@"asset":userAsset}];
            
//            self_weak_.topView.cbtCountLabel.text =  [NSString stringWithFormat:@"%@  AKB",[DecimalNumberTool formatNumberWithString:[CBTLocalUserManager sharedInstance].userAsset isAssets:YES]];
            [source setResult:@{@"key": @"success",@"name":@"AssetRequest"}];
        }
        else {
            [source setError:[NSError errorWithDomain:@"ErrorDomain" code:-1 userInfo:@{@"name":@"AssetRequest"}]];
        }
    }];
    return source.task;
}

- (BFTask *)checkIDcardStatus
{
    @weak(self)
    
    BFTaskCompletionSource *source = [BFTaskCompletionSource taskCompletionSource];
    
    [UserManager checkIDcardWithUserId:[CBTLocalUserManager sharedInstance].userId block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal) {
            NSString *flag = [data[@"data"]objectForKey:@"flag"];
            [[CBTLocalUserManager sharedInstance] refreshUserInfoDic:@{@"flag":flag}];
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
            [self_weak_.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            [source setResult:@{@"key": @"success",@"name":@"checkIDcardRequest"}];
        }
        else {
            [source setError:[NSError errorWithDomain:@"ErrorDomain" code:-1 userInfo:@{@"name":@"checkIDcardRequest"}]];
        }
    }];
    return source.task;
}

- (BFTask *)checkUserSiginStatus
{
    @weak(self)
    BFTaskCompletionSource *source = [BFTaskCompletionSource taskCompletionSource];
    [UserManager checkIDcardStatusWithBlock:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal) {
            NSString *flag = [data[@"data"]objectForKey:@"signInFlag"];
            [[CBTLocalUserManager sharedInstance] refreshUserInfoDic:@{@"signInFlag":flag}];
            [self_weak_.topView refreshSignInStatus:flag];
            [source setResult:@{@"key": @"success",@"name":@"checkUserSigindRequest"}];
        }
        else {
            [source setError:[NSError errorWithDomain:@"ErrorDomain" code:-1 userInfo:@{@"name":@"checkUserSigindRequest"}]];
        }
    }];
    return source.task;
}


-(void)allRequest
{
    @weak(self)
    [[BFTask taskForCompletionOfAllTasks:@[[self getAssetMsg], [self checkIDcardStatus],[self checkUserSiginStatus]]] continueWithBlock:^id _Nullable(BFTask * _Nonnull t) {
        [self_weak_.tableView.mj_header endRefreshing];
        return nil;
    }];
}

- (void)changeLanguage {
    self.cellDataArray = @[@{@"image":@"wode_cundan",
                             @"title":kLocalizedString(@"我的收益", nil)},
                           @{@"image":@"mine_yingjian",
                             @"title":kLocalizedString(@"PC硬件", nil)},
                           @{@"image":@"mine_yaoqing",
                             @"title":kLocalizedString(@"邀请好友", nil)},
                           /*@{@"image":@"mine_contact",
                             @"title":kLocalizedString(@"联系我们", nil)},*/
                           @{@"image":@"wode_mimashezhi",
                             @"title":kLocalizedString(@"密码设置", nil)},
                           @{@"image":@"wode_yuyanqiehuan",
                            @"title":kLocalizedString(@"语言切换", nil)},
                           @{@"image":@"wode_gengxin",
                             @"title":kLocalizedString(@"检查更新", nil)}];
    [self.tableView reloadData];
    [_subMitBtn setTitle:kLocalizedString(@"退出登录", nil) forState:(UIControlStateNormal)];
    [self.topView refreshSignInStatus:[CBTLocalUserManager sharedInstance].signInFlag];
    
    NSString *avatar    = [CBTLocalUserManager sharedInstance].avatar;
    NSString *avatarStr = [NSString stringWithFormat:@"%@：%@",kLocalizedString(@"邀请码", nil),[CBTLocalUserManager sharedInstance].avatar];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:avatarStr];
    [string setAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.],NSForegroundColorAttributeName: [UIColor whiteColor]} range:NSMakeRange(0, avatarStr.length - avatar.length + 1)];
    [string setAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.],NSForegroundColorAttributeName: DefaultBlueColor} range:NSMakeRange(avatarStr.length - avatar.length, avatar.length)];
    
    self.topView.userIDLabel.attributedText = string;
}

- (void)signOutAction:(UIButton *)btn
{
    [HFAlert showHFNewAlertInViewController:self title:kLocalizedString(@"确定要注销当前账户吗？",nil) message:nil cancleButtonTitle:kLocalizedString(@"取消",nil) okButtonTitle:kLocalizedString(@"确定",nil) cancelClickHandle:nil okClickHandle:^{
        [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:HEFANTV_TOKEN];
        [[CBTLocalUserManager sharedInstance]removeUserInfo];
        [((AppDelegate*)[UIApplication sharedApplication].delegate) changeRootVC];
    }];
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.cellDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell"];
    cell.indexRow = indexPath.row;
    cell.dataSourceDic = self.cellDataArray[indexPath.row];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        MyDepositSlipViewController *vc = [[MyDepositSlipViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.row == 1){
        WCOrderAndAddrVC *vc = [[WCOrderAndAddrVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.row == 2){
        InviteFriendsViewController *vc = [[InviteFriendsViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
//    else if (indexPath.row == 3){
//        [HFStatusView showSuccessMessage:kLocalizedString(@"敬请期待",nil)];
//        return;
////        WContactUSVC *vc = [[WContactUSVC alloc]init];
////        [self.navigationController pushViewController:vc animated:YES];
//    }
    else if (indexPath.row == 3){
        SettingPassWordViewController *vc = [[SettingPassWordViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.row == 4) {
        LanguageChangeViewController *vc = [[LanguageChangeViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else{
        [self startClearBgColorLoading];
        
        @weak(self)
        [NetWork requestWithURL:Network_CheckIOSUpdate params:nil httpMethod:@"GET" finishedBlock:^(NSURLSessionDataTask *task, id  _Nullable result) {
            [self stopLoading];
            NSString *localVerson =  [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];
            NSString *nowVerson = [result[@"data"]objectForKey:@"version_code"];
            BOOL isUpData = [nowVerson compare:localVerson options:NSNumericSearch] == NSOrderedDescending;
            if (isUpData) {
                NSString *updateAddr = [result[@"data"]objectForKey:@"url"];
                [HFAlert showHFAlertInViewController:self_weak_ title:[NSString stringWithFormat:@"%@V%@",kLocalizedString(@"发现新版本",nil),nowVerson] message:nil cancleButtonTitle:kLocalizedString(@"取消",nil) okButtonTitle:kLocalizedString(@"更新",nil) cancelClickHandle:nil okClickHandle:^{
                    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:updateAddr] options:@{} completionHandler:^(BOOL success) {
                        NSLog(@"成功");
                    }];
                }];
            }
            else{
                [HFStatusView showSuccessMessage:kLocalizedString(@"当前已是最新版",nil)];
            }
        } failureBlock:^(NSURLSessionDataTask *task, NSError *error) {
            [self stopLoading];
            [HFStatusView showSuccessMessage:kLocalizedString(@"当前已是最新版",nil)];
        }];
    }
}

- (void)updateLevel:(NSInteger)level {
    NSString *str;
    switch (level) {
        case 0:
            str = @"vip0";
            break;
        case 1:
            str = @"vip1";
            break;
        case 2:
            str = @"vip2";
            break;
        case 3:
            str = @"vip3";
            break;
        case 4:
            str = @"vip4";
            break;
        case 5:
            str = @"vip5";
            break;
        default:
            str = @"vip0";
            break;
    }
    self.topView.signInImageView.image = [UIImage imageNamed:str];
}

#pragma mark - Lazy

- (UIButton *)subMitBtn
{
    if (!_subMitBtn) {
        _subMitBtn = [[UIButton alloc]initWithFrame:CGRectMake(25,0, ScreenNarrowSide - 50, 40)];
        [_subMitBtn setTitle:kLocalizedString(@"退出登录", nil) forState:(UIControlStateNormal)];
        [_subMitBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        _subMitBtn.backgroundColor = UIColorFromRGB(0xFF5101);
        [_subMitBtn addTarget:self action:@selector(signOutAction:) forControlEvents:(UIControlEventTouchUpInside)];
        _subMitBtn.layer.cornerRadius  = 20;
        _subMitBtn.layer.masksToBounds = YES;
        _subMitBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    }
    return _subMitBtn;
}

//- (UIImageView *)bgImageView
//{
//    if (!_bgImageView) {
//        _bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenNarrowSide, 190)];
//        _bgImageView.image = [UIImage imageNamed:@"wode_beijing"];
//    }
//    return _bgImageView;
//}

- (MyTopView *)topView
{
    if (!_topView) {
        __weak MyViewController *weakSelf = self;
        _topView = [[MyTopView alloc]initWithFrame:CGRectMake(0, 0, ScreenWideSide, HFTopStatusHeight + 100)];
        [_topView setPushUserInfoBlock:^(NSInteger type){
            if (type == 0) {
                UserInfoChangeViewController *userInfoVC = [[UserInfoChangeViewController alloc]init];
                [weakSelf.navigationController pushViewController:userInfoVC animated:YES];
            }
            else if (type == 1) {
                UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                WithdrawViewController *registerVC = [story instantiateViewControllerWithIdentifier:@"WithdrawID"];
                [registerVC setWithdrawFinishBlock:^(NSString * _Nonnull asset) {
//                    weakSelf.topView.cbtCountLabel.text =[NSString stringWithFormat:@"%@ AKB",[DecimalNumberTool formatNumberWithString:asset isAssets:YES]];
                }];
                [weakSelf.navigationController pushViewController:registerVC animated:YES];
            }
            else {
                if ([[CBTLocalUserManager sharedInstance].signInFlag intValue] == 1) {
                    [HFStatusView showFailureMessage:kLocalizedString(@"已签到",nil)];
                }
                else {
                    [weakSelf startClearBgColorLoading];
                    [UserManager getUserSignInByuserIdWithBlock:^(id data, HttpRequestResult result, NSString *msg) {
                        [weakSelf stopLoading];
                        if (result == kHttpRequestResultNormal) {
                            [[CBTLocalUserManager sharedInstance] refreshUserInfoDic:@{@"signInFlag":@"1"}];
                            NSString *flag = [NSString stringWithFormat:@"%@",[data[@"data"]objectForKey:@"rewardAmount"]];
                            if ([NSString isBlankString:flag] || ![NSString deptNumInputShouldNumber:flag] ||  [flag intValue] <= 0) {
                                 [HFStatusView showSuccessMessage:kLocalizedString(@"签到成功, +",nil)];
                            }
                            else {
                                [HFStatusView showSuccessMessage:[NSString stringWithFormat:@"%@%@%@PC",kLocalizedString(@"签到成功, +",nil),flag,kLocalizedString(@"个",nil)]];
                                [weakSelf getAssetMsg];
                            }
                            [weakSelf.topView refreshSignInStatus:@"1"];
                        }
                        else {
                            [HFStatusView showFailureMessage:msg];
                        }
                    }];
                }
            }
        }];
    }
    return _topView;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenNarrowSide, ScreenWideSide - self.tabBarController.tabBar.bounds.size.height) style:(UITableViewStylePlain)];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellEditingStyleNone;
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        if (@available(iOS 11.0, *)){
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else{
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight           = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        
        [_tableView registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil] forCellReuseIdentifier:@"myCell"];

        _tableView.tableHeaderView = self.topView;
        
        UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenNarrowSide, 100)];
        footerView.backgroundColor = [UIColor clearColor];
        _subMitBtn = [[UIButton alloc]initWithFrame:CGRectMake(25,0, ScreenNarrowSide - 50, 40)];
        [_subMitBtn setTitle:kLocalizedString(@"退出登录", nil) forState:(UIControlStateNormal)];
        [_subMitBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        _subMitBtn.backgroundColor = UIColorFromRGB(0xFF5101);
        [_subMitBtn addTarget:self action:@selector(signOutAction:) forControlEvents:(UIControlEventTouchUpInside)];
        _subMitBtn.layer.cornerRadius = 20;
        _subMitBtn.centerY = 50;
        _subMitBtn.layer.masksToBounds = YES;
        _subMitBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [footerView addSubview:_subMitBtn];
         _tableView.tableFooterView = footerView;
        
        __weak MyViewController *weakSelf = self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf allRequest];
        }];
    }
    return _tableView;
}

@end
